package com.billdowney.qq.robot.plugins.provide;

import cn.hutool.core.io.FileUtil;
import com.billdowney.qq.robot.annotations.HookMethod;
import com.billdowney.qq.robot.annotations.HookNotice;
import com.billdowney.qq.robot.bean.ConfigBean;
import com.billdowney.qq.robot.enums.RobotEventEnum;
import com.billdowney.qq.robot.plugins.RobotPlugin;
import com.billdowney.qq.robot.plugins.RobotPluginContent;
import com.billdowney.qq.robot.util.MessageUtil;
import kotlin.io.FilesKt;
import net.mamoe.mirai.event.events.MemberJoinEvent;
import net.mamoe.mirai.event.events.MemberLeaveEvent;
import net.mamoe.mirai.message.data.At;
import net.mamoe.mirai.message.data.MessageChainBuilder;
import net.mamoe.mirai.utils.BotConfiguration;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Objects;

/**
 * 群管理插件
 *
 * @author BillDowney
 * @date 2021/4/7 20:12
 */
@Component
@HookNotice(name = "群管理插件", start = true)
public class GroupManageRobotPlugin implements RobotPlugin, InitializingBean {
    @Autowired
    private ConfigBean configBean;
    private File welcomeImgDir;

    @Override
    public void afterPropertiesSet() throws Exception {
        // 媒体文件夹
        File baseMediaPath = FilesKt.resolve(BotConfiguration.getDefault().getWorkingDir(), configBean.getWorkspace() + File.separator + "media" + File.separator);
        this.welcomeImgDir = FilesKt.resolve(baseMediaPath, "welcome_img");
        FileUtil.mkdir(this.welcomeImgDir);
    }

    @HookMethod(desc = "自动欢迎入群成员", event = {RobotEventEnum.MEMBER_JOIN})
    public void joinGroup(RobotPluginContent content) {
        MemberJoinEvent event = (MemberJoinEvent) content.getEvent();
        MessageChainBuilder builder = MessageUtil.createBuilder();
        builder.append(new At(event.getMember().getId()));
        builder.append(Objects.requireNonNull(MessageUtil.buildImageMessage(event.getGroup(), com.billdowney.qq.robot.util.FileUtil.randomFile(this.welcomeImgDir))));
        content.putReplyMessage(event.getGroup(), builder.build());
    }

    @HookMethod(desc = "自动提示退出群成员信息", event = {RobotEventEnum.MEMBER_LEAVE})
    public void leaveGroup(RobotPluginContent content) {
        // 发一条消息到群里
        MemberLeaveEvent event = content.getMemberLeaveEvent();
        // 构建链式消息
        MessageChainBuilder messageChainBuilder = new MessageChainBuilder();
        configBean.getRootManageQq().forEach(item -> {
            At at = new At(item);
            messageChainBuilder.append(at);
        });
        messageChainBuilder.append(String.format("\n有人离开了：%s(%s)", event.getMember().getNick(), event.getMember().getId()));
        content.putReplyMessage(event.getGroup(), messageChainBuilder);
    }
}
